package com.jinzhi.jzweb.controller.api;



import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import cn.afterturn.easypoi.word.WordExportUtil;
import cn.afterturn.easypoi.word.entity.WordImageEntity;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jinzhi.common.base.BaseController;
import com.jinzhi.common.constants.ConstMessages;
import com.jinzhi.common.constants.MessagesEnum;
import com.jinzhi.common.utils.Result;
import com.jinzhi.common.utils.ShiroUtils;
import com.jinzhi.common.utils.StringUtil;
import com.jinzhi.jzapi.domain.UserDO;
import com.jinzhi.jzapi.utils.JWTUtil;
import com.jinzhi.jzapi.utils.JinZhiException;
import com.jinzhi.jzapi.utils.RedisUtil;
import com.jinzhi.jzweb.domain.*;
import com.jinzhi.jzweb.domain.vo.AuntUserVO;
import com.jinzhi.jzweb.service.*;
import com.jinzhi.sys.service.UserService;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;

/**
 * 
 * <pre>
 * 月嫂模块相关接口
 * </pre>
 * <small> 2023-04-18 09:19:00 | Long</small>
 */
@RestController
@RequestMapping("/jzApi/jazUserAunt")
public class ApiJazUserAuntController extends BaseController {

	//获取项目的根路径
	@Value("${easypoi.path}")
	private String classPath;

	@Autowired
	private JazUserAuntService jazUserAuntService; //月嫂表

	@Autowired
	private UserService userService; //用户表

	@Autowired
	private JazSysLabelService jazSysLabelService; //标签表

	@Autowired
	private JazSysProjectService jazSysProjectService; //服务表

	@Autowired
	private JazUserOrderService jazUserOrderService; //签约订单表

	@Autowired
	private JazUserCommentService jazUserCommentService; //月嫂评价表

	@Autowired
	private JazUserIntegralService jazUserIntegralService; //积分明细表

	@Autowired
	private JazSysContractService jazSysContractService; //积分明细表

	@Autowired
	private JazInterviewService jazInterviewService; //面试邀约表

	@Autowired
	private JazSysProjectTypeService jazSysProjectTypeService; //面试邀约表

	@Autowired
	private JazMessageService jazMessageService;

	@Autowired
	private JazUserCommentDescriptionService jazUserCommentDescriptionService;


	int selUserIntegral = 10; //查看月嫂信息所用积分

	int getUserTelephoneIntegral = 100; //拨打电话所需积分


	@Autowired
	private JazSysContractTemplateService jazSysContractTemplateService;


	/**
	 * 可用标签下拉框查询
	 * @return
	 */
	@GetMapping("/sleLabel")
	public Result<List<JazSysLabelDO>> sleLabel(){
		EntityWrapper<JazSysLabelDO> wrapper = new EntityWrapper<JazSysLabelDO>();
		wrapper.eq("status",0);//查询未禁用的标签
		List<JazSysLabelDO> sysLabelDOS = jazSysLabelService.selectList(wrapper);
		return Result.ok(sysLabelDOS);
	}




	@GetMapping("/sleProjectType")
	public Result<Map> sleProjectType(Long id){
		JazSysProjectDO jazSysProjectDO = jazSysProjectService.selectById(id);
		Map map= new HashMap();
		map.put("state",jazSysProjectDO.getMultipleChoice()); //是否多选

		EntityWrapper<JazSysProjectTypeDO> wrapper = new EntityWrapper<JazSysProjectTypeDO>();
		wrapper.eq("sys_project_id",id);
		List<JazSysProjectTypeDO> jazSysProjectTypeDOS = jazSysProjectTypeService.selectList(wrapper);
		map.put("jazSysProjectTypeDOS",jazSysProjectTypeDOS);
		return Result.ok(map);
	}



	/**
	 * 可用项目下拉框查询
	 * @return
	 */
	@GetMapping("/sleProject")
	public Result<List<JazSysProjectDO>> sleProject(){
		EntityWrapper<JazSysProjectDO> wrapper = new EntityWrapper<JazSysProjectDO>();
		wrapper.eq("status",0);//查询未禁用的项目
		List<JazSysProjectDO> jazSysProjectDOS = jazSysProjectService.selectList(wrapper);
		return Result.ok(jazSysProjectDOS);
	}






	/**
	 * 查看当前角色权限   0.普通用户  1.月嫂
	 * @return
	 */
	@GetMapping("/getUserRole")
	public Result<?> getUserRole(){
		UserDO getUser = JWTUtil.getUser();
		UserDO userDO = userService.selectById(getUser.getId());
		EntityWrapper<JazUserAuntDO> wrapper = new EntityWrapper<JazUserAuntDO>();
		wrapper.eq("sys_userid",userDO.getId());
		wrapper.eq("audit_result","0");
		JazUserAuntDO jazUserAuntDO = jazUserAuntService.selectOne(wrapper);
		if (jazUserAuntDO == null){    //如果 == null表示没有认证月嫂
			return Result.ok(0);
		}else {
			return Result.ok(1);
		}
	}







	/**
	 * 月嫂取消入驻
	 * @return
	 */
	@GetMapping("/cancelUserAunt")
	public Result<?> cancelUserAunt(){
		UserDO getUser = JWTUtil.getUser();
		UserDO userDO = userService.selectById(getUser.getId());
//		UserDO userDO = userService.selectById(1328881670693347330L);

		EntityWrapper<JazUserAuntDO> wrapper = new EntityWrapper<JazUserAuntDO>();
		wrapper.eq("sys_userid",userDO.getId());
		jazUserAuntService.delete(wrapper);
		return Result.ok();
	}






	/**
	 * 月嫂信息回显
	 * @return
	 */
	@GetMapping("/selUserAunt")
	public Result<?> selUserAunt(){
		UserDO getUser = JWTUtil.getUser();
		UserDO userDO = userService.selectById(getUser.getId());
		AuntUserVO auntUserVO =new AuntUserVO();
		auntUserVO.setSysUserid(String.valueOf(userDO.getId()));
		AuntUserVO rstAuntUserVO = jazUserAuntService.selAuntUserOne(auntUserVO);
		return Result.ok(rstAuntUserVO);
	}




	private static String bs = ",";


	private static List<String> splitStrArrayList(String str) {
		List<String> stringList = new ArrayList<>();
		if (str != null) {
			String[] strs = str.split(bs);
			stringList.addAll(Arrays.asList(strs));
			return stringList;
		}
		return null;
	}




	/**
	 * 月嫂列表查询
	 * @return
	 */
	@GetMapping("/selUserAuntList")
	public Result<?> selUserAuntList(AuntUserVO auntUserVO,int current, int size) throws ParseException, UnsupportedEncodingException {
		Page<AuntUserVO> rstAuntUserPageVO=jazUserAuntService.selAuntUserListPage(auntUserVO,current,size);
		List<AuntUserVO> rstAuntUserVOs = rstAuntUserPageVO.getRecords();

		for (int j=0;j<rstAuntUserVOs.size();j++){
			SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");

			if (rstAuntUserVOs.get(j).getSigningStatus() == 1){ //已经签约的用户 查询剩余签约天数
				EntityWrapper<JazUserOrderDO> wrapper = new EntityWrapper<JazUserOrderDO>();
				wrapper.eq("initiate_id",rstAuntUserVOs.get(j).getSysUserid()).or().eq("signing_id",rstAuntUserVOs.get(j).getSysUserid());
				wrapper.andNew().eq("conclude_status",2); //已经签署
				wrapper.andNew().ne("status",3);//不等于已取消
				wrapper.andNew().ne("status",2);//不等于已取消
				JazUserOrderDO jazUserOrderDO = jazUserOrderService.selectOne(wrapper);
				if (jazUserOrderDO!=null){
					Date endTime =jazUserOrderDO.getEndTime();
					int dayBetweenTwoDate = daysBetween(format.format(new Date()),format.format(endTime));
					rstAuntUserVOs.get(j).setSigningDate(dayBetweenTwoDate);
				}
			}
			if (StringUtil.notEmpty(rstAuntUserVOs.get(j).getLabelId())) {
				//多个标签查询
				List<String> labelList = splitStrArrayList(rstAuntUserVOs.get(j).getLabelId());
				rstAuntUserVOs.get(j).setLabelId(""); //清空标签id值
				for (int i = 0; i < labelList.size(); i++) {
					JazSysLabelDO jazSysLabelDO = jazSysLabelService.selectById(labelList.get(i)); //查询标签表
					if ("".equals(rstAuntUserVOs.get(j).getLabelId())) { //如果labelid是空的
						rstAuntUserVOs.get(j).setLabelId(jazSysLabelDO.getDescribe());
					} else {
						String le = rstAuntUserVOs.get(j).getLabelId() + "," + jazSysLabelDO.getDescribe();
						rstAuntUserVOs.get(j).setLabelId(le);
					}
				}
			}

			if (StringUtil.notEmpty(rstAuntUserVOs.get(j).getProjectId())) {
				//多个服务查询
				List<String> projectList = splitStrArrayList(rstAuntUserVOs.get(j).getProjectId());
				rstAuntUserVOs.get(j).setProjectId(""); //清空服务id值
				for (int i = 0; i < projectList.size(); i++) {
					JazSysProjectDO jazSysProjectDO = jazSysProjectService.selectById(projectList.get(i));//查询服务表
					if ("".equals(rstAuntUserVOs.get(j).getProjectId())) { //如果ProjectId是空的
						rstAuntUserVOs.get(j).setProjectId(jazSysProjectDO.getName());
					} else {
						String pr = rstAuntUserVOs.get(j).getProjectId() + "," + jazSysProjectDO.getName();
						rstAuntUserVOs.get(j).setProjectId(pr);
					}
				}
			}
			rstAuntUserVOs.get(j).setLabelIds(splitStrArrayList(rstAuntUserVOs.get(j).getLabelId()));

//			rstAuntUserVOs.get(j).setName(rstAuntUserVOs.get(j).getName().substring(0,1) + "阿姨");
		}
		rstAuntUserPageVO.setRecords(rstAuntUserVOs);
		return Result.ok(rstAuntUserPageVO);
	}




	/**
	 * JAVA计算两个日期相差多少天
	 * @param date1str
	 * @param date2str
	 * @return
	 */
	public static int daysBetween(String date1str,String date2str) throws ParseException {
		int count = 0;
		if("".equals(date1str) || date1str == null || "".equals(date2str) || date2str == null) {
			return count;
		}
		SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
		Date date1 = format.parse(date1str);
		Date date2 = format.parse(date2str);
		count = Math.abs((int) ((date1.getTime() - date2.getTime()) / (1000*3600*24)));
		return count;
	}







	/**
	 * 是否使用积分查询月嫂详情
	 * @return
	 */
	@GetMapping("/isSelUserAuntParticulars")
	public Result<?> isSelUserAuntParticulars (String id){
		UserDO getUser = JWTUtil.getUser();
		UserDO userDO = userService.selectById(getUser.getId());
//		UserDO userDO = userService.selectById(1328881670693347330L);
		String key = "userParticulars" + userDO.getId() + id;
		if (RedisUtil.get(key) == null){
			return Result.ok(0); //已过期不能查看
		}else {
			return Result.ok(1); //可以查看
		}
	}







	/**
	 * 查询月嫂信息扣除积分接口
	 * @return
	 */
	@GetMapping("/selUserAuntDeduct")
	public Result<?> selUserAuntDeduct (String id){
		UserDO getUser = JWTUtil.getUser();
		UserDO userDO = userService.selectById(getUser.getId());
//		UserDO userDO = userService.selectById(1328881670693347330L);
		String key = "userParticulars" + userDO.getId() + id;

		if (userDO.getCurrentPoints() == null){
			userDO.setCurrentPoints("0"); //如果为null就默认0积分
		}

		if (Double.valueOf(userDO.getCurrentPoints()) < selUserIntegral){
			return Result.ok(0);
		}
		userDO.setCurrentPoints(String.valueOf(Double.valueOf(userDO.getCurrentPoints()) -  selUserIntegral));

		JazUserIntegralDO jazUserIntegralDO = new JazUserIntegralDO();
		jazUserIntegralDO.setIntegralDetail("-"+selUserIntegral); //积分
		jazUserIntegralDO.setSysUserid(userDO.getId()); //用户id
		jazUserIntegralDO.setIntegralTime(new Date()); //时间
		jazUserIntegralDO.setIntegralWay("查看月嫂信息"); //用途
		jazUserIntegralDO.setCurrentIntegral(userDO.getCurrentPoints()); //当前积分
		jazUserIntegralService.insert(jazUserIntegralDO);

		userService.updateById(userDO);
		RedisUtil.set(key,"查询月嫂详情2小时内有效",7200);
		return Result.ok();
	}






	/**
	 * 是否使用积分查看电话号码
	 * @return
	 */
	@GetMapping("/isSelUserTelephone")
	public Result<?> isSelUserTelephone (String id){
		UserDO getUser = JWTUtil.getUser();
		UserDO userDO = userService.selectById(getUser.getId());
		String key = "selUserTelephone" + userDO.getId() + id;
		if (RedisUtil.get(key) == null){
			return Result.ok(0); //已过期不能查看
		}else {
			return Result.ok(1); //可以查看
		}
	}



	/**
	 * 查询月嫂电话扣除积分
	 * @return
	 */
	@GetMapping("/selUserTelephone")
	public Result<?> selUserTelephone(String id){
		UserDO getUser = JWTUtil.getUser();
		UserDO userDO = userService.selectById(getUser.getId());

		String key = "selUserTelephone" + userDO.getId() + id;

		if (userDO.getCurrentPoints() == null){
			userDO.setCurrentPoints("0"); //如果为null就默认0积分
		}

		if (Double.valueOf(userDO.getCurrentPoints()) < getUserTelephoneIntegral){
			return Result.ok(0);
		}
		userDO.setCurrentPoints(String.valueOf(Double.valueOf(userDO.getCurrentPoints()) -  getUserTelephoneIntegral));

		JazUserIntegralDO jazUserIntegralDO = new JazUserIntegralDO();
		jazUserIntegralDO.setIntegralDetail("-"+getUserTelephoneIntegral); //积分
		jazUserIntegralDO.setSysUserid(userDO.getId()); //用户id
		jazUserIntegralDO.setIntegralTime(new Date()); //时间
		jazUserIntegralDO.setIntegralWay("拨打月嫂电话"); //用途
		jazUserIntegralDO.setCurrentIntegral(userDO.getCurrentPoints()); //当前积分
		jazUserIntegralService.insert(jazUserIntegralDO);


		userService.updateById(userDO);
		RedisUtil.set(key,"查询月嫂电话24小时内有效",86400);
		return Result.ok();
	}




	/**
	 * 查询月嫂口碑评价
	 * @return
	 */
	@GetMapping("/selUserAuntComment")
	public Result<?> selUserAuntComment (String auntUserId){
		EntityWrapper<JazUserCommentDO> wrapper = new EntityWrapper<JazUserCommentDO>();
		wrapper.eq("commentd_objectid",auntUserId);
        List<JazUserCommentDO> jazUserCommentDOS = jazUserCommentService.selectList(wrapper);
        for (int i=0;i<jazUserCommentDOS.size();i++){
			UserDO userDO = userService.selectById(jazUserCommentDOS.get(i).getCommentUserid());
			jazUserCommentDOS.get(i).setName(userDO.getNickname());
			jazUserCommentDOS.get(i).setUserImg(userDO.getHeadPortrait());
			List commentDescriptionContext =new ArrayList();
			String[] commentDescriptionId = jazUserCommentDOS.get(i).getCommentDescriptionId().split(",");
			for (int j =0;j<commentDescriptionId.length;j++){
				JazUserCommentDescriptionDO jazUserCommentDescriptionDO = jazUserCommentDescriptionService.selectById(commentDescriptionId[j]);
				commentDescriptionContext.add(jazUserCommentDescriptionDO.getCommentDescription());//平江描述
			}
			jazUserCommentDOS.get(i).setCommentDescriptionContext(commentDescriptionContext);
        }
		return Result.ok(jazUserCommentDOS);
    }





	/**
	 * 月嫂详情查询
	 * bs == 0从列表进 id传的月嫂id，bs == 1 从消息进id传的用户id
	 * @return
	 */
	@GetMapping("/selUserAuntParticulars")
	public Result<?> selUserAuntParticulars(String id) throws ParseException {
		AuntUserVO auntUserVO =new AuntUserVO();
		auntUserVO.setId(Long.valueOf(id));
		AuntUserVO rstAuntUserPageVO = jazUserAuntService.selAuntUserOne(auntUserVO);
		SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");

		if (rstAuntUserPageVO.getSigningStatus() == 1){ //已经签约的用户 查询剩余签约天数
			EntityWrapper<JazUserOrderDO> wrapper = new EntityWrapper<JazUserOrderDO>();
			wrapper.eq("initiate_id",rstAuntUserPageVO.getSysUserid()).or().eq("signing_id",rstAuntUserPageVO.getSysUserid());
			wrapper.andNew().eq("conclude_status",2); //已经签署
			wrapper.andNew().ne("status",3);//不等于已取消
			wrapper.andNew().ne("status",2);//不等于已取消
			Date endTime = jazUserOrderService.selectOne(wrapper).getEndTime();
			int dayBetweenTwoDate = daysBetween(format.format(new Date()),format.format(endTime));
			rstAuntUserPageVO.setSigningDate(dayBetweenTwoDate);
		}

		if (StringUtil.notEmpty(rstAuntUserPageVO.getLabelId())) {
			//多个标签查询
			List<String> labelList = splitStrArrayList(rstAuntUserPageVO.getLabelId());
			rstAuntUserPageVO.setLabelId(""); //清空标签id值
			for (int i = 0; i < labelList.size(); i++) {
				JazSysLabelDO jazSysLabelDO = jazSysLabelService.selectById(labelList.get(i)); //查询标签表
				if ("".equals(rstAuntUserPageVO.getLabelId())) { //如果labelid是空的
					rstAuntUserPageVO.setLabelId(jazSysLabelDO.getDescribe());
				} else {
					String le = rstAuntUserPageVO.getLabelId() + "," + jazSysLabelDO.getDescribe();
					rstAuntUserPageVO.setLabelId(le);
				}
			}
		}
		if (StringUtil.notEmpty(rstAuntUserPageVO.getProjectId())) {
			//多个服务查询
			List<String> projectList = splitStrArrayList(rstAuntUserPageVO.getProjectId());
			rstAuntUserPageVO.setProjectId(""); //清空服务id值
			for (int i = 0; i < projectList.size(); i++) {
				JazSysProjectDO jazSysProjectDO = jazSysProjectService.selectById(projectList.get(i));//查询服务表
				if ("".equals(rstAuntUserPageVO.getProjectId())) { //如果ProjectId是空的
					rstAuntUserPageVO.setProjectId(jazSysProjectDO.getName());
				} else {
					String pr = rstAuntUserPageVO.getProjectId() + "," + jazSysProjectDO.getName();
					rstAuntUserPageVO.setProjectId(pr);
				}
			}
		}
//		rstAuntUserPageVO.setName(rstAuntUserPageVO.getName().substring(0,1) + "阿姨");
		rstAuntUserPageVO.setLabelIds(splitStrArrayList(rstAuntUserPageVO.getLabelId()));
        rstAuntUserPageVO.setNurseContents(splitStrArrayList(rstAuntUserPageVO.getNurseContent()));
        rstAuntUserPageVO.setExaminationConditions(splitStrArrayList(rstAuntUserPageVO.getExaminationCondition()));

        rstAuntUserPageVO.setSkills(splitStrArrayList(rstAuntUserPageVO.getSkill()));

		return Result.ok(rstAuntUserPageVO);
	}





	/**
	 * 订单合同导出
	 * @return
	 */
	@GetMapping("/userOrderExport")
	@ResponseBody
	public void userOrderExport (String orderId,HttpServletResponse response){
		JazUserOrderDO jazUserOrderDO = jazUserOrderService.selectById(orderId);
		JazSysContractTemplateDO jazSysContractDO = jazSysContractTemplateService.selectById(jazUserOrderDO.getContractId());
		String filename ="";
		String wjm = "";
		if (jazSysContractDO.getName().contains("月嫂")){
			wjm = "ysht";
		}
		if (jazSysContractDO.getName().contains("育儿嫂")){
			wjm = "yrsht";
		}
		if (jazSysContractDO.getName().contains("养老护理")){
			wjm = "ylhlht";
		}
		if (jazSysContractDO.getName().contains("医护照料")){
			wjm = "yhzlht";
		}
		if (jazSysContractDO.getName().contains("保姆")){
			wjm = "bmht";
		}
		if (jazSysContractDO.getName().contains("产后恢复")){
			wjm = "chhfht";
		}
		if (jazSysContractDO.getName().contains("钟点工")){
			wjm = "zdght";
		}
		if (jazSysContractDO.getName().contains("催乳")){
			wjm = "crht";
		}
		try {
			documentWord(jazUserOrderDO,response,filename,wjm);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}





	private void documentWord(JazUserOrderDO jazUserOrderDO,HttpServletResponse response,String filename,String wjm) throws Exception{
		//导出组装数据
		Map<String,Object> params =new HashMap<>();
		params.put("jfxm",jazUserOrderDO.getNameJia()); //甲方姓名
		params.put("jfsfzhm",jazUserOrderDO.getIdentityCardJia()); //甲方身份证号码
		params.put("jfzz", jazUserOrderDO.getAddress()); //甲方地址
		params.put("jflxdh",jazUserOrderDO.getPhoneJia()); //甲方电话

		//甲方手写签名
		WordImageEntity jfImageEntity =new WordImageEntity();
		jfImageEntity.setHeight(40);
		jfImageEntity.setWidth(34);
		String jfurl = jazUserOrderDO.getSignatureJia();
		String jffName = jfurl.trim();
		jffName = jffName.substring(jffName.lastIndexOf("/")+1);
		String savePath = RootPath("/img");


		System.out.println("++++++++++++++++++++++++++++++++++++++乙方图片："+savePath);


		//将阿里云链接存到本地
		download(jfurl,jffName,savePath);
		jfImageEntity.setUrl(RootPath("/img/"+jffName));
		jfImageEntity.setType(WordImageEntity.URL);
		params.put("jfqm",jfImageEntity);//甲方签名



		params.put("yfxm", jazUserOrderDO.getNameYi()); //乙方姓名
		params.put("yfsfzhm",jazUserOrderDO.getIdentityCardYi()); //甲方身份证号码
		params.put("yfzz", jazUserOrderDO.getHomeAddressYi()); //甲方地址
		params.put("yflxdh",jazUserOrderDO.getPhoneYi()); //甲方电话

		//甲方手写签名
		WordImageEntity yfImageEntity =new WordImageEntity();
		yfImageEntity.setHeight(40);
		yfImageEntity.setWidth(34);
		String yfurl = jazUserOrderDO.getSignatureYi();
		String yffName = yfurl.trim();
		yffName = yffName.substring(yffName.lastIndexOf("/")+1);
		String yfsavePath = RootPath("/img");
		System.out.println("++++++++++++++++++++++++++++++++++++++乙方图片："+yfsavePath);

		//将阿里云链接存到本地
		download(yfurl,yffName,yfsavePath);
		yfImageEntity.setUrl(RootPath("/img/"+yffName));
		yfImageEntity.setType(WordImageEntity.URL);
		params.put("yfqm",yfImageEntity);//乙方签名


		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
		String[] ksArray = splitStrArray(sdf.format(jazUserOrderDO.getStartTime()));
		String[] jsArray = splitStrArray(sdf.format(jazUserOrderDO.getEndTime()));

		params.put("ksn",ksArray[0]); //服务开始 年
		params.put("ksy",ksArray[1]); //服务开始 月
		params.put("ksr",ksArray[2]); //服务开始 日

		params.put("jsn",jsArray[0]); //服务结束 年
		params.put("jsy",jsArray[1]); //服务结束 月
		params.put("jsr",jsArray[2]); //服务结束 日

		params.put("fwdz",jazUserOrderDO.getAddress());//服务地址

		params.put("xz",jazUserOrderDO.getTotalPrice()); //薪资
		params.put("htrq",sdf.format(jazUserOrderDO.getCreateTime())); //合同签订日期


		XWPFDocument word = WordExportUtil.exportWord07(templateFile(wjm).getPath(),params);

		response.setHeader("content-disposition","attachment;filename="+new String(filename.getBytes(),"ISO8859-1"));
		response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
		word.write(response.getOutputStream());
	}





	public String[] splitStrArray(String str) {
		if (str != null) {
			return str.split("-");
		}
		return null;
	}






	/**
	 * 私有处理方法
	 */
	private String RootPath(String u_path) {
		String rootPath = "";
		//windows下
		if ("\\".equals(File.separator)) {
			//System.out.println(classPath);
			rootPath = classPath + u_path;
			rootPath = rootPath.replaceAll("/", "\\\\");
			if (rootPath.substring(0, 1).equals("\\")) {
				rootPath = rootPath.substring(1);
			}
		}
		//linux下
		if ("/".equals(File.separator)) {
			//System.out.println(classPath);
			rootPath = classPath + u_path;
			rootPath = rootPath.replaceAll("\\\\", "/");
		}
		return rootPath;
	}





	//获取docx文件位置
	private File templateFile(String wjm){
		File templateFile= new File(RootPath("/"+wjm+".docx"));
		System.out.printf("++++++++++++++++++++++++++++++++++++++++++++++"+templateFile.getPath());
		return templateFile;
	}



	/*根据阿里云地址保存到本地*/
	public void download(String urlString, String filename,String savePath) throws Exception {
		// 构造URL
		URL url = new URL(urlString);
		// 打开连接
		URLConnection con = url.openConnection();
		//设置请求超时为5s
		con.setConnectTimeout(5*1000);
		// 输入流
		InputStream is = con.getInputStream();
		// 1K的数据缓冲
		byte[] bs = new byte[1024];
		// 读取到的数据长度
		int len;
		// 输出的文件流
		File sf=new File(savePath);
		if(!sf.exists()){
			sf.mkdirs();
		}
		OutputStream os = new FileOutputStream(sf.getPath()+"/"+filename);
		// 开始读取
		while ((len = is.read(bs)) != -1) {
			os.write(bs, 0, len);
		}
		// 完毕，关闭所有链接
		os.close();
		is.close();
	}
























	//张唐清


	/**
	 * 根据当前时间判断今天刷新按钮是否已经使用过
	 * */
	@PostMapping("/whetherrefresh")
	@ResponseBody
	public  Result<?> whetherrefresh(){
		int whetherrefresh = jazUserAuntService.whetherrefresh();
		return Result.ok(whetherrefresh);
	}


	/**
	 /**
	 * 月嫂简历-刷新一次使用20积分-每天只能刷新一次-刷新前判断是否积分足够不过返回积分不够提示
	 * */
	@PostMapping("/curriculumVitaeRefresh")
	@ResponseBody
	public Result<?> curriculumVitaeRefresh(){
		int result = jazUserAuntService.curriculumVitaeRefresh();
		return Result.ok(result);
	}






	/**
	 * 查询用户面试状态  1未发起，2,已发起,3已通过,4已拒绝
	 * @return
	 */
	@GetMapping("/selInterviewStatus")
	public Result<?> selInterviewStatus(Long userAuntId){
		int rst = 0;
		UserDO getUser = JWTUtil.getUser();
		//根据邀约人和被邀约人查询看该用户是否邀约过该月嫂进行面试
		EntityWrapper<JazInterviewDO> wrapper =new EntityWrapper<>();
		wrapper.eq("inviter_id",getUser.getId()); //邀约人
		JazUserAuntDO jazUserAuntDO = jazUserAuntService.selectById(userAuntId);//查询出月嫂信息
		wrapper.eq("invitee_id",jazUserAuntDO.getSysUserid()); //被邀约人，月嫂userId
		JazInterviewDO jazInterviewDO = jazInterviewService.selectOne(wrapper);
		if (jazInterviewDO!=null){
				rst=2;
				if (jazInterviewDO.getInterStatus() == 1){ //同意邀约
					if (jazInterviewDO.getResult() == 1){
						rst =3;
						return Result.ok(rst);
					}
					if (jazInterviewDO.getResult() == 2){
						rst=4;
						return Result.ok(rst);
					}
				}else { //拒绝邀约
					rst=4;
				}
			return Result.ok(rst);
		}else {
			rst=1;
			return Result.ok(rst);
		}
	}


	/**
	 *
	 * @param userAuntId  阿姨id
	 * @param projectId   项目id
	 * @param interviewTime  面试日期
	 * @param address  面试地址
	 * @param interviewFormat 面试形式( 0 线下 1 线上)
	 * @param workAddress 工作地址
	 * @param workMoney 工作薪资范围
	 * @param workContent 工作内容
	 * @param workTime 工作日期
	 * @return
	 */
	@PostMapping("/sponsorInterviewStatus")
	public Result<?> sponsorInterviewStatus(Long userAuntId,String projectId,Date interviewTime,String address,int interviewFormat,String workAddress,String workMoney,String workContent,Date workTime,Date endTime){
		UserDO getUser = JWTUtil.getUser();
		//根据邀约人和被邀约人查询看该用户是否邀约过该月嫂进行面试
		EntityWrapper<JazInterviewDO> wrapper =new EntityWrapper<>();
		wrapper.eq("inviter_id",getUser.getId()); //邀约人
		wrapper.eq("invitee_id",userAuntId); //被邀约人，月嫂id
		JazInterviewDO jazInterviewDO = jazInterviewService.selectOne(wrapper);
		if (jazInterviewDO!=null){
			return Result.ok("操作失败，该用户已发起过面试");
		}

		JazUserAuntDO jazUserAuntDO = jazUserAuntService.selectById(userAuntId);  //查询出月嫂信息


		JazInterviewDO innertJazInterviewDO = new JazInterviewDO();
		innertJazInterviewDO.setInviterId(getUser.getId()); //邀约人userId
		innertJazInterviewDO.setInviteeId(jazUserAuntDO.getSysUserid()); //被邀约人userId
		innertJazInterviewDO.setProjectId(projectId); //服务类型
		innertJazInterviewDO.setStatus(1);//状态已发送
		innertJazInterviewDO.setCreateTime(new Date()); //创建时间
		innertJazInterviewDO.setInterviewTime(interviewTime); //面试时间
		innertJazInterviewDO.setInterviewAddress(address);//面试地址
		innertJazInterviewDO.setInterviewFormat(interviewFormat);//面试形式 0线下 1线上
		innertJazInterviewDO.setWorkAddress(workAddress); //工作地址
		innertJazInterviewDO.setWorkMoney(workMoney); //工作薪资
		innertJazInterviewDO.setWorkContent(workContent); //工作内容
		innertJazInterviewDO.setWorkTime(workTime); //工作开始日期
		innertJazInterviewDO.setEndTime(endTime); //工作结束日期
		jazInterviewService.insert(innertJazInterviewDO);


		JazMessageDO jazMessageDO1 = new JazMessageDO();
		jazMessageDO1.setMessageType(2); //订单消息
		jazMessageDO1.setSenderId(getUser.getId()); //发送人
		jazMessageDO1.setReceiverId(jazUserAuntDO.getSysUserid()); //接收人
		jazMessageDO1.setMessageContent(MessagesEnum.MESSAGE_204.getMsg());
		jazMessageDO1.setMessageNum(MessagesEnum.MESSAGE_204.getNum());
		jazMessageDO1.setHasSendSms(true);
		jazMessageDO1.setInterviewId(innertJazInterviewDO.getId());
		jazMessageDO1.setIsRead(0);
		jazMessageService.senMessage(jazMessageDO1);


		JazMessageDO jazMessageDO2 = new JazMessageDO();
		jazMessageDO2.setMessageType(1); //系统消息
		jazMessageDO2.setSenderId(getUser.getId()); //发送人
		jazMessageDO2.setReceiverId(getUser.getId()); //接收人
		jazMessageDO2.setMessageContent(MessagesEnum.MESSAGE_201.getMsg());
		jazMessageDO2.setMessageNum(MessagesEnum.MESSAGE_201.getNum());
		jazMessageDO2.setInterviewId(innertJazInterviewDO.getId());
		jazMessageDO2.setIsRead(0);
		jazMessageService.senMessage(jazMessageDO2);


		return Result.ok();
	}

}
